﻿using System.Net;
using System.Text;

namespace Battle.Net.Infrastructure
{
    internal class JsonFetcher
    {
        private readonly WebClient _webClient;

        public JsonFetcher()
        {
            _webClient = new WebClient {Credentials = null, Proxy = null, Encoding = Encoding.UTF8};
        }

        public JsonFetcher(WebClient webClient)
        {
            _webClient = webClient;
            _webClient.Encoding = Encoding.UTF8;
        }

        private static JsonFetcher _instance;

        public static string Fetch(string authorization, string url)
        {
            if (_instance == null)
                _instance = new JsonFetcher();

            var authHeader = _instance._webClient.Headers[HttpRequestHeader.Authorization];
            if (authHeader != null) _instance._webClient.Headers.Remove(HttpRequestHeader.Authorization);

            _instance._webClient.Headers.Add(HttpRequestHeader.Authorization, authorization);

            return Fetch(url);
        }

        public static string Fetch(string url)
        {

            if (_instance == null)
                _instance = new JsonFetcher();

            try
            {
                var authHeader = _instance._webClient.Headers[HttpRequestHeader.Authorization];
                if (authHeader != null) _instance._webClient.Headers.Remove(HttpRequestHeader.Authorization);

                var client = _instance._webClient;
                var json =  client.DownloadString(url);
                return json;
            }
            catch (WebException webex)
            {
                Logging.Log.Error(webex.Message, webex);
                throw;
            }

        }
    }
}

